﻿using AutoMapper;
using B.S.BasicData.Api.Write.Applications.Commands.Accounts;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastcuture.Commons;
using B.S.BasicData.Infrastcuture.Interfaces;
using MediatR;
using System.Transactions;
using Yitter.IdGenerator;

namespace B.S.BasicData.Api.Write.Applications.CommandHandlers.Accounts
{
    public class AddQueryCommandHandler : IRequestHandler<AddQueryCommand, ApiResult<object>>
    {
        private readonly IBaseRepository<UserInfo> baseRepository;
        private readonly IMapper mapper;
        private readonly IBaseRepository<NlogInfo> baseRepository1;


        public AddQueryCommandHandler(IBaseRepository<UserInfo> baseRepository, IMapper mapper, IBaseRepository<NlogInfo> baseRepository1)
        {
            this.baseRepository = baseRepository;
            this.mapper = mapper;
            this.baseRepository1 = baseRepository1;
        }

        public async Task<ApiResult<object>> Handle(AddQueryCommand request, CancellationToken cancellationToken)
        {
            ApiResult<object> result = new ApiResult<object>();
            result.Code = ResultCode.AddSuccess;
            result.Message = ResultCode.AddSuccess.Description();
            //开始事务
            using(var trans=new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    UserInfo user = mapper.Map<UserInfo>(request);
                    await baseRepository.Add(user);
                    NlogInfo nlog = new NlogInfo();
                    nlog.NlogId = YitIdHelper.NextId();
                    nlog.NlogName = "添加操作";
                    nlog.Context = $"{request.UserName}添加了一条数据";
                    nlog.NlogTime = DateTime.Now;
                    await baseRepository1.Add(nlog);
                    
                    //提交事务
                    trans.Complete();
                    return await Task.FromResult(result);

                }
                catch (Exception)
                {

                    throw;
                }


            }
            
            
        }
    }
}
